<?php
if (! defined ( 'sugarEntry' ) || ! sugarEntry)
	die ( 'Not A Valid Entry Point' );

/**
 * *******************************************************************************
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc.
 * Copyright (C) 2004-2010 SugarCRM Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 *
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 * ******************************************************************************
 */
	
// for editor load cutomisations
require_once ('modules/edanz_Schedule/EditorLoad.php');

global $timedate;
function template_echo_slice_activities_shared(& $args, $additional_details, $textColor) {
	global $app_list_strings, $app_strings, $shared_user, $timedate, $current_language;
	
	$current_module_strings = return_module_language ( $current_language, 'edanz_Schedule' );
	
	$schedule_note_image = SugarThemeRegistry::current ()->getImageURL ( 'schedule_note.gif' );
	
	$additional_details ['schedule_notes'] = str_replace ( array (
			"&#039",
			"'" 
	), '\&#039', $additional_details ['schedule_notes'] );
	
	if (! empty ( $additional_details ['schedule_notes'] )) {
		$extra = "onmouseover=\"return overlib('" . str_replace ( array (
				"\rn",
				"\r",
				"\n" 
		), array (
				'',
				'',
				'<br />' 
		), $additional_details ['schedule_notes'] ) . "', CAPTION, '{$current_module_strings['LBL_SCHEDULE_NOTES']}" . "', DELAY, 200, STICKY, MOUSEOFF, 1000, WIDTH, " . (empty ( $additional_details ['width'] ) ? '330' : $additional_details ['width']) . ", CLOSETEXT, '<img border=0  style=\'margin-left:2px; margin-right: 2px;\' src=" . SugarThemeRegistry::current ()->getImageURL ( 'close.gif' ) . ">', " . "CLOSETITLE, '{$app_strings['LBL_ADDITIONAL_DETAILS_CLOSE_TITLE']}', CLOSECLICK, FGCLASS, 'olFgClass', " . "CGCLASS, 'olCgClass', BGCLASS, 'olBgClass', TEXTFONTCLASS, 'olFontClass', CAPTIONFONTCLASS, 'olCapFontClass', CLOSEFONTCLASS, 'olCloseFontClass');\" " . "onmouseout=\"return nd(1000);\" ";
		
		echo "<span $extra><img width='15' height='15' 	 class='' border='0' src='$schedule_note_image'>";
	}
	
	echo "</span>";
	
	// Start of Task breakdown
	if (empty ( $args ['slice']->acts_arr [$shared_user->id] )) {
		return;
	}
	$task_count = 0;
	$work_load = Array ();
	$workload_breakdown = Array ();
	$origin_systems = Array ();
	
	foreach ( $args ['slice']->acts_arr [$shared_user->id] as $act ) {
		if ($act->sugar_bean->object_name == 'Task') {
			if (! empty ( $act->sugar_bean->type ) && ! empty ( $act->sugar_bean->workload )) {
				$task_count ++;
				if ($act->sugar_bean->status != 'Deferred') {
					if (! array_key_exists ( $act->sugar_bean->type, $work_load )) {
						$work_load [$act->sugar_bean->type] = Array ();
					}
					array_push ( $work_load [$act->sugar_bean->type], $act->sugar_bean->workload );
				}
				if (! in_array ( $act->sugar_bean->origin_system, $origin_systems )) {
					array_push ( $origin_systems, $act->sugar_bean->origin_system );
				}
				$task = array (
						"type" => $act->sugar_bean->type,
						"origin_system" => $act->sugar_bean->origin_system,
						"origin_module" => $act->sugar_bean->origin_module,
						"origin_id" => $act->sugar_bean->origin_id,
						"workload" => $act->sugar_bean->workload,
						"status" => $act->sugar_bean->status,
						"name" => $act->sugar_bean->name,
						"id" => $act->sugar_bean->id 
				);
				array_push ( $workload_breakdown, $task );
			}
		}
	}
	if ($task_count > 0) {
		
		$breakdown_element_id = $shared_user->id . $args ['slice']->end_time->ts;
		
		echo "<div >";
		
		$page_sum = 0;
		// Get workload point from tasks by id
		foreach ( $workload_breakdown as $task ) {
			$task_point = getTaskLoadById ( $task ['id'] );
			$page_sum = $page_sum + $task_point;
		}
		echo "<font color=#434343>";
		echo $page_sum . "&nbsp;|&nbsp;";
		echo "</font>";
		
		echo "<a style=\"text-decoration:none\" href=\"javascript: toggleDisplay('" . $breakdown_element_id . "');\" title=\"" . $app_strings ['LBL_TOGGLE_BREAKDOWN'] . "\">";
		$work_load_index = count ( $work_load );
		foreach ( $work_load as $key => $val ) {
			echo "" . getShortLetter ( $app_list_strings ['task_type_dom'] [$key] ) . '(' . array_sum ( $val ) . ")&nbsp;";
			if ($key + 1 != $work_load_index) {
				// echo "&nbsp;|&nbsp;";
			}
		}
		
		$deferred_tasks = array_filter ( $workload_breakdown, function ($element) use($origin) {
			return ($element ['status'] == 'Deferred');
		} );
		if (count ( $deferred_tasks )) {
			echo "R/A(" . count ( $deferred_tasks ) . ")";
		}
		echo "</a>";
		echo "<div id=\"" . $breakdown_element_id . "\" style=\"display:none\">";
		foreach ( $origin_systems as $origin ) {
			$origin_filtered_tasks = array_filter ( $workload_breakdown, function ($element) use($origin) {
				return ($element ['origin_system'] == $origin);
			} );
			usort ( $origin_filtered_tasks, function ($func_a, $func_b) {
				return strcmp ( $func_a ['name'], $func_b ['name'] );
			} );
			echo "<table class=\"yui-calendar\" width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" border=\"0\"><tbody>";
			echo "<tr><th colspan=4><strong>" . $app_list_strings ['origin_systems'] [$origin] . "</strong></th></tr>";
			foreach ( $origin_filtered_tasks as $task ) {
				echo "<tr>";
				echo "<td><a href=\"" . $task ['origin_system'] . "/index.php?action=DetailView&module=" . $task ['origin_module'] . "&record=" . $task ['origin_id'] . "\" target=\"_blank\">" . $task ['name'] . "</a></td>";
				echo "<td>" . $task ['workload'] . ' ' . $app_list_strings ['task_type_units'] [$task ['type']] . "</td>";
				echo "<td>" . getTaskLoadById ( $task ['id'] ) . "</td>";
				echo "<td>" . $app_list_strings ['task_type_dom'] [$task ['type']] . "</td>";
				echo "<td";
				switch ($task ['status']) {
					case 'Deferred' :
						echo " class=\"calcell highlight3\"";
						break;
					case 'Completed' :
						echo " class=\"calcell highlight4\"";
						break;
				}
				echo ">" . $app_list_strings ['task_status_dom'] [$task ['status']] . "</td>";
				echo "</tr>";
			}
			echo "</tbody></table>";
		}
		echo "</div>";
	}
}
function getTaskLoadById($taskId) {
	$query = "select workload_point from tasks t where t.deleted=0 and t.status <> 'Deferred' and  t.id='$taskId'";
	$db = DBManagerFactory::getInstance ();
	$r = $db->query ( $query );
	$point = 0;
	while ( $a = $db->fetchByAssoc ( $r ) ) {
		$point = $a ['workload_point'];
	}
	return $point;
}
function getTaskPoint($assigned_user_id, $today) {
	$query = "SELECT  sum(workload_point) workload_point FROM tasks t WHERE  t.deleted=0 and t.status <> 'Deferred' and t.assigned_user_id = '$assigned_user_id' and date_add(date_due, interval +8 hour)>='$today' ORDER BY t.date_due desc  ";
	$db = DBManagerFactory::getInstance ();
	$r = $db->query ( $query );
	$point = 0;
	while ( $a = $db->fetchByAssoc ( $r ) ) {
		$point = $a ['workload_point'];
	}
	return $point;
}
function getLastDateHasTask($assigned_user_id) {
	$query = "SELECT max(DATE(date_add(date_due, interval +8 hour) )) date_due  FROM tasks t WHERE t.deleted=0 and t.status <> 'Deferred' and t.assigned_user_id = '$assigned_user_id' ORDER BY t.date_due desc  ";
	$db = DBManagerFactory::getInstance ();
	$r = $db->query ( $query );
	$date_due;
	while ( $a = $db->fetchByAssoc ( $r ) ) {
		$date_due = $a ['date_due'];
	}
	return $date_due;
}
function getArray_Workload_point($assigned_user_id, $today) {
	$query = "SELECT sum(workload_point) as workload_point, DATE_FORMAT(date_add(date_due, interval +8 hour), '%Y-%m-%d') as date_due FROM tasks t WHERE  t.deleted=0 and t.status <> 'Deferred' and date_add(date_due, interval +8 hour)>='$today' and t.assigned_user_id = '$assigned_user_id'  group by DATE_FORMAT(date_add(date_due, interval +8 hour), '%Y%m%d') ORDER BY date_due desc  ";
	$db = DBManagerFactory::getInstance ();
	$r = $db->query ( $query );
	$Array_workload_point = array ();
	while ( $a = $db->fetchByAssoc ( $r ) ) {
		$Array_workload_point = $Array_workload_point + array (
				$a ['date_due'] => $a ['workload_point'] 
		);
	}
	return $Array_workload_point;
}
function getShortLetter($taskName) {
	if ($taskName == "First Edit") {
		echo 'FE';
	} else if ($taskName == "Clarification") {
		echo 'CE';
	} else if ($taskName == "CLD Review") {
		echo 'CLD';
	} else if ($taskName == "Reviewer Recommendation") {
		echo 'RR';
	} else if ($taskName == "Expert Scientific Review") {
		echo 'ESR';
	} else if ($taskName == "Rewriting") {
		echo 'RW';
	} else if ($taskName == "Quote") {
		echo 'Q';
	} else if ($taskName == "Journal Selection") {
		echo 'JS';
	} else if ($taskName == "Abstract Development") {
		echo 'AD';
	} else if ($taskName == "Formatting") {
		echo 'F';
	} else if ($taskName == "Cover Letter Development") {
		echo 'CLD';
	} else if ($taskName == "Internal Review") {
		echo 'IR';
	} else if ($taskName == "Complaint") {
		echo 'C';
	} else if ($taskName == "Project Management") {
		echo 'PM';
	} else if ($taskName == "Writing") {
		echo 'W';
	} else if ($taskName == "JS Review") {
		echo 'JR';
	} else {
		echo $taskName;
	}
}
// ///////////////////////////////
// template
// ///////////////////////////////
function template_schedule(& $args) {
	global $timedate;
	
	$newargs = array ();
	$newargs ['calendar'] = $args ['calendar'];
	
	global $ids;
	global $current_user;
	global $mod_strings;
	global $app_list_strings, $current_language, $currentModule, $action, $app_strings;
	$current_module_strings = return_module_language ( $current_language, 'edanz_Schedule' );
	$ids = array ();
	$user_ids = $current_user->getPreference ( 'shared_ids' );
	// get list of user ids for which to display data
	if (! empty ( $user_ids ) && count ( $user_ids ) != 0 && ! isset ( $_REQUEST ['shared_ids'] )) {
		$ids = $user_ids;
	} elseif (isset ( $_REQUEST ['shared_ids'] ) && count ( $_REQUEST ['shared_ids'] ) > 0) {
		$ids = $_REQUEST ['shared_ids'];
		$current_user->setPreference ( 'shared_ids', $_REQUEST ['shared_ids'] );
	} else {
		// $ids = get_user_array(false);
		// $ids = array_keys($ids);
		$ids = array (
				$current_user->id 
		);
	}
	
	echo '<script type="text/javascript" src="' . getJSPath ( 'include/javascript/sugar_grp_overlib.js' ) . '"></script>';
	echo '<script type="text/javascript" src="' . getJSPath ( 'include/javascript/postmessage.js' ) . '"></script>';
	
	$tools = '<div align="right"><a href="index.php?module=' . $currentModule . '&action=' . $action . '&view=shared" class="tabFormAdvLink">&nbsp;<a href="javascript: toggleDisplay(\'shared_cal_edit\');" class="tabFormAdvLink">' . SugarThemeRegistry::current ()->getImage ( 'edit', 'alt="' . $current_module_strings ['LBL_EDIT'] . '"  border="0"  align="absmiddle"' ) . '&nbsp;' . $current_module_strings ['LBL_EDIT'] . '</a></div>';
	
	echo get_form_header ( $current_module_strings ['LBL_SELECTED_EDITORS'], $tools, false );
	if (empty ( $_SESSION ['shared_ids'] ))
		$_SESSION ['shared_ids'] = "";
	
	echo "<div id='shared_cal_edit' style='display: none;'>
		<form name='shared_cal' action=\"index.php\" method=\"get\" >
		<input type=\"hidden\" name=\"module\" value=\"" . $currentModule . "\">
		<input type=\"hidden\" name=\"action\" value=\"" . $action . "\">
		<input type=\"hidden\" name=\"view\" value=\"shared\">
		<input type=\"hidden\" name=\"edit\" value=\"0\">";
	
	require_once ('include/templates/TemplateGroupChooser.php');
	$chooser = new TemplateGroupChooser ();
	
	echo "<script>SUGAR.tabChooser.freezeOptions('display_tabs', 'hide_tabs', 'Home');</script>";
	
	$chooser->display_hide_tabs = true;
	// $chooser->display_hide_tabs = false;
	
	$chooser->args ['id'] = 'edit_tabs';
	// $chooser->args['values_array'][1] = get_user_array(false, ''); //$controller->get_tabs($focus);
	$chooser->args ['values_array'] [1] = get_bean_select_array ( false, 'edanz_Editor', 'CONCAT(first_name, \' \', last_name)', '(is_group = 0 AND employee_status = \'Active\')', 'first_name, last_name' );
	
	// $chooser->args['values_array'][1] = $ids;
	foreach ( $ids as $id ) {
		global $locale;
		$query = "SELECT first_name, last_name FROM users WHERE id like '$id' AND deleted=0 ";
		$query .= " ORDER BY last_name ASC";
		$db = DBManagerFactory::getInstance ();
		$r = $db->query ( $query );
		$ret = array ();
		while ( $a = $db->fetchByAssoc ( $r ) ) {
			$chooser->args ['values_array'] [0] [$id] = $locale->getLocaleFormattedName ( $a ['first_name'], $a ['last_name'] );
		}
		unset ( $chooser->args ['values_array'] [1] [$id] );
	}
	
	$chooser->args ['left_name'] = 'shared_ids';
	$chooser->args ['right_name'] = 'hidden_ids';
	
	$chooser->args ['left_label'] = $current_module_strings ['LBL_DISPLAY_EDITORS'];
	$chooser->args ['right_label'] = $current_module_strings ['LBL_HIDE_EDITORS'];
	$chooser->args ['title'] = $current_module_strings ['LBL_SELECT_USERS'];
	
	echo "<table cellpadding=\"0\" cellspacing=\"3\" border=\"0\" align=\"center\">
		<tr><td valign=\"top\">";
	echo $chooser->display ();
	
	?>

</td>
</tr>
<tr>
	<td align="left" colspan="2"><input class="button" type="button"
		onclick="set_chooser(); this.form.submit();"
		title="<?php echo $app_strings['LBL_SELECT_BUTTON_TITLE'] ?>"
		accessKey="<?php echo $app_strings['LBL_SELECT_BUTTON_KEY']?>"
		value="<?php echo $app_strings['LBL_SELECT_BUTTON_LABEL'] ?>" /><input
		class="button" onClick="javascript: toggleDisplay('shared_cal_edit');"
		type="button"
		title="<?php echo $app_strings['LBL_CANCEL_BUTTON_TITLE'] ?>"
		accessKey="<?php echo $app_strings['LBL_CANCEL_BUTTON_KEY'] ?>"
		value="<?php echo $app_strings['LBL_CANCEL_BUTTON_LABEL'] ?>" /></td>
</tr>
</table>

<script type="text/javascript" language="Javascript">
<!--  to hide script contents from old browsers

function set_chooser()
{



var shared_ids_def = '';

var display_td = document.getElementById('shared_ids_td');

var display_ref = display_td.getElementsByTagName('select')[0];

for(i=0; i < display_ref.options.length ;i++)
{
//         shared_ids_def += "shared_ids[]="+display_ref.options[i].value+"&";
        display_ref.options[i].selected = "1";
}

//document.shared_cal.shared_ids_def.value = shared_ids_def;

}
// end hiding contents from old browsers  -->
</script>

</form>

</div>
</p>
<a id='001'></a>
<?php
	if (isset ( $_REQUEST ['edit'] ) && $_REQUEST ['edit'])
		echo " <script language=\"javascript\"> toggleDisplay('shared_cal_edit'); </script>";
	?>
<table id="daily_cal_table_outside" width="100%" border="0"
	cellpadding="0" cellspacing="0" class="monthBox">
	<tr>
		<td>
			<table width="100%" border="0" cellpadding="0" cellspacing="0"
				class="monthHeader">
				<tr>
					<td width="1%" nowrap>
<?php
	if (! isset ( $args ['size'] ) || $args ['size'] != 'small') {
		template_get_previous_calendar ( $args );
	}
	?>

		  </td>
					<td width=" 98 % " align=center scope='row'>
						<h3>
<?php template_echo_date_info($args['calendar']->date_time); ?>
</h3>
					</td>
					<td align="right" width="1%" nowrap><?php
	
	if (! isset ( $args ['size'] ) || $args ['size'] != 'small') {
		template_get_next_calendar ( $args );
	}
	?> </td>
				</tr>
			</table>
		</td>
	</tr>
	<tr>
		<td>
			<table cellspacing="0" cellpadding="0" class="monthBox">
<?php
	global $current_user, $shared_user;
	$shared_args = array ();
	foreach ( $args as $key => $val ) {
		$shared_args [$key] = $val;
	}
	$shared_args ['calendar'] = $args ['calendar'];
	// $shared_args['average_punctuality'] = get_punctuality();
	// $shared_user = new User();
	require_once ('modules/edanz_Editor/edanz_Editor.php');
	$shared_user = new edanz_Editor ();
	echo '<strong><font color="black" >Points: '.$_REQUEST['point'].'</strong></font>';
	echo "&nbsp;&nbsp;&nbsp;";
	echo '<strong><font color="black" >Due Date: '.$_REQUEST['due'].'</strong></font>';
	foreach ( $ids as $member ) {
		$shared_user->retrieve ( $member );
		$shared_args ['calendar']->show_tasks = true;
		$shared_args ['calendar']->add_activities ( $shared_user );
		$shared_args ['show_link'] = 'off';
		if (($shared_user->id == $current_user->id))
			$shared_args ['show_link'] = 'on';
		echo '<tr><td class="monthCalBody" nowrap="nowrap" >';
		editor_name_heading ();
		echo '</td><td class="monthCalBody">';
		get_schedule_notes_and_probation_notes ();
		getUserTime ();
		echo '</td><td class="monthCalBody" colspan="12">';
		get_average_quality_rating ();
		get_desired_workload ();
		get_available_for_job();
		echo '</td></tr>';
		echo '<tr class="monthCalBody">';
		$array_workload_point = get_balance_workload_point ( $shared_args );
		template_calendar_horizontal ( $shared_args, $array_workload_point );
		echo '</tr>';
	}
	?>
</table>
		</td>
	</tr>
	<tr>
		<td>
			<table width="100%" cellspacing="0" cellpadding="0"
				class="monthFooter">
				<tr>
					<td width="50%"><?php template_get_previous_calendar($args); ?></td>
					<td align="right" width="50%"><?php template_get_next_calendar($args); ?></td>
				</tr>
			</table>

		</td>
	</tr>
</table>
<?php
}
function template_calendar_horizontal(& $args, $array_workload_point) {
	global $app_strings, $shared_user;
	// echo "<table id=\"daily_cal_table\" border=\"0\" cellpadding=\"0\" cellspacing=\"1\" width=\"100%\"><tr>";
	
	// need to change these values after we find out what activities
	// occur outside of these values
	echo "<td width=400 style='padding:0;border:1px solid #abc3d7;'>";
	echo "<div style=\"m\">
    <a href=\"javascript: toggleDisplay('" . $shared_user->id . "');\" title=\"" . $app_strings ['LBL_TOGGLE_BREAKDOWN'] . "\"><table cellpadding=\"1\" cellspacing=\"0\" border=\"0\" width=\"100%\" class=\"\"><tbody><tr><td><img src='themes/default/images/create-record.gif'>&nbsp;" . $app_strings ['LBL_TOGGLE_BREAKDOWNTASKHISTORY'] . "</td></tr></tbody></table></a></div>";
	echo "<div id=\"" . $shared_user->id . "\" style=\"display:none\">";
	echo editor_historic_rates ();
	echo "</div></td>";
	$start_slice_idx = $args ['calendar']->get_start_slice_idx ();
	$end_slice_idx = $args ['calendar']->get_end_slice_idx ();
	$cur_slice_idx = 1;
	for($cur_slice_idx = $start_slice_idx; $cur_slice_idx <= $end_slice_idx; $cur_slice_idx ++) {
		$calendar = $args ['calendar'];
		$args ['slice'] = $calendar->slice_hash [$calendar->slices_arr [$cur_slice_idx]];
		template_cal_horizontal_slice ( $args, $array_workload_point );
	}
	// echo "</tr></table>";
}
function template_cal_horizontal_slice(& $args, $array_workload_point) {
	global $shared_user;
	require_once ('modules/edanz_Editor/metadata/additionalDetails.php');
	$additional_details = scheduleDetails ( $shared_user->id, $args ['slice']->start_time );
	// Signal Unavailability
	$cell_style = "border:1px solid #ABC3D7;";
	if ($additional_details ['unavailable']) {
		$cell_style .= "background-color:#C1C1C1;";
	}
	if ($args ['slice']->start_time->day_of_week == 0 || $args ['slice']->start_time->day_of_week == 6) {
		if (! $additional_details ['unavailable'])
			$cell_style .= "background-color:#DDDDDD;";
	}
	
	if(generateDate($args ['slice']->start_time) == $_REQUEST['due']){
		$cell_style .= "border:3px solid #3dc46d;";
	}
	// For change the backgroud red if work load point is lesser than 0
	// $slice = $args['slice'];
	// $today = date('y-m-d',time());
	// $start_time = generateDate($slice->start_time);
	// $date_due = getLastDateHasTask($shared_user->id);
	// if(strtotime($today) <= strtotime($start_time) && strtotime($date_due) >= strtotime($start_time) && $array_workload_point[$start_time] != null && $array_workload_point[$start_time] != 0){
	// if($array_workload_point[$start_time] < 0){
	// $cell_style .= "background-color:#e06666;";
	// }
	// }
	
	echo "<td width=\"7%\" style=\"" . $cell_style . "\" scope='row' valign=\"top\">";
	//echo "<td width=\"7%\" style='border:1px solid #3dc46d;' scope='row' valign=\"top\">";
	
	$textColor = template_echo_slice_date_nolink ( $args, $additional_details, $array_workload_point );
	
	template_echo_slice_activities_shared ( $args, $additional_details, $textColor );
	// custom_template_echo_slice_activities_shared($args);
	echo "</td>";
}
/**
 * To make workload point banlance everyday which is not over FTE
 * 
 * @param unknown_type $args        	
 */
function get_balance_workload_point($args) {
	global $shared_user;
	$today = date ( 'y-m-d', time () );
	// the WLU should not shift to today, so the calculation will start from tomorrow.
	$today =  date ( 'Y-m-d', strtotime ( "$today +1 day" ) );
	$array_workload_point = getArray_Workload_point ( $shared_user->id, $today );
	$FTE = get_desired_workload_value ();
	$date_due = getLastDateHasTask ( $shared_user->id );
	$DateDifferent = getDateDifferent ( $date_due, $today );
	$date_loop = $date_due;
	// Loop from today to last day has task, to display FTE if workload point over it, set rest of workload point(point-FTE) to previous day
	// Cross the day if has Unavailability schdule note and weekend.
	for($workload = 0; $workload < $DateDifferent + 1; $workload ++) {
		$workload_point_values = $array_workload_point [$date_loop];
		$scheduleNotes = getScheduleNotes ( $shared_user->id, $date_loop );
		if ($scheduleNotes || date ( 'w', strtotime ( $date_loop ) ) == 0 || date ( 'w', strtotime ( $date_loop ) ) == 6) {
			$array_workload_point [$date_loop] = 0;
			$date_loop = date ( 'Y-m-d', strtotime ( "$date_loop -1 day" ) );
			$array_workload_point [$date_loop] = $array_workload_point [$date_loop] + $workload_point_values;
		} else if ($workload_point_values > $FTE) {
			// if not last time for loop
			if ($DateDifferent + 1 - $workload != 1) {
				$workload_point_loop = $workload_point_values - $FTE;
				if ($FTE - $workload_point_values < 0) {
					// if the points can't be distributed to another day, then continue to show the available workload as a red, negative number.
					if ($FTE - $array_workload_point [date ( 'Y-m-d', strtotime ( "$date_loop -1 day" ) )] < 0) {
						$array_workload_point [$date_loop] = $FTE - $workload_point_values;
					} else {
						$array_workload_point [$date_loop] = "0";
						$date_temp = date ( 'Y-m-d', strtotime ( "$date_loop -1 day" ) );
						$array_workload_point [$date_temp] = $array_workload_point [$date_temp] + $workload_point_loop;
					}
				} else {
					$array_workload_point [$date_loop] = $FTE - $workload_point_values;
					$date_temp = date ( 'Y-m-d', strtotime ( "$date_loop -1 day" ) );
					$array_workload_point [$date_temp] = $array_workload_point [$date_temp] + $workload_point_loop;
				}
				$date_loop = date ( 'Y-m-d', strtotime ( "$date_loop -1 day" ) );
			} else {
				$array_workload_point [$date_loop] = $FTE - $workload_point_values;
			}
		} else {
			$array_workload_point [$date_loop] = $FTE - $workload_point_values;
			$date_loop = date ( 'Y-m-d', strtotime ( "$date_loop -1 day" ) );
			continue;
		}
	}
	return $array_workload_point;
}

/**
 * Check an editor if has Unavailability schduele note in a specific date.
 * 
 * @param string $assigned_user_id        	
 * @param date $date_loop        	
 * @return if has Unavailability schduele note return true, otherwise return false
 */
function getScheduleNotes($assigned_user_id, $date_loop) {
	$query = "select name from edanz_schedulenotes e where e.deleted = '0' and type in ('ReceiptUnavailability','ReturnUnavailability') and e.related_editor_id= '$assigned_user_id' and  (valid_from BETWEEN '$date_loop' and '$date_loop' or  valid_to BETWEEN '$date_loop' and '$date_loop') ";
	$db = DBManagerFactory::getInstance ();
	$r = $db->query ( $query );
	$scheduleNotes = false;
	while ( $a = $db->fetchByAssoc ( $r ) ) {
		if (! empty ( $a ['name'] )) {
			$scheduleNotes = true;
		}
	}
	return $scheduleNotes;
}

/**
 * Generate week and date for each canlender cell
 * 
 * @param unknown_type $args        	
 * @param unknown_type $additional_details        	
 * @param unknown_type $array_workload_point        	
 */
function template_echo_slice_date_nolink(& $args, $additional_details, $array_workload_point) {
	global $mod_strings, $shared_user;
	$date_due = getLastDateHasTask ( $shared_user->id );
	$slice = $args ['slice'];
	$today = date ( 'y-m-d', time () );
	$start_time = generateDate ( $slice->start_time );
	$textColor = "#434343";
	if (strtotime ( $today ) == strtotime ( $start_time )) {
		echo "<div style='float:left'><strong><font color=\"" . $textColor . "\">" . $slice->start_time->get_day_of_week_short ();
		echo "&nbsp;";
		echo $slice->start_time->get_day ();
		echo "</strong></font></div>";
		if (strtotime ( $today ) <= strtotime ( $start_time ) && strtotime ( $date_due ) >= strtotime ( $start_time ) && $array_workload_point [$start_time] != null) {
			if ($array_workload_point [$start_time] <= 0) {
				$textColor = "red";
			}
			echo "<div style='text-align:right;float:right'><font color=\"" . $textColor . "\"><strong>";
			if ($array_workload_point [$start_time] == 0) {
				echo 0;
			}else{
				echo sprintf("%.2f",$array_workload_point [$start_time]);
			}
			echo "</strong>&nbsp;</font></div>";
		}
		echo "</br>";
	} else {
		echo "<div style='float:left'><font color=\"" . $textColor . "\">" . $slice->start_time->get_day_of_week_short ();
		echo "&nbsp;";
		echo $slice->start_time->get_day ();
		echo "</font></div>";
		if (strtotime ( $today ) <= strtotime ( $start_time ) && strtotime ( $date_due ) >= strtotime ( $start_time ) && $array_workload_point [$start_time] != null) {
			if ($array_workload_point [$start_time] <= 0) {
				$textColor = "red";
			}
			echo "<div style='text-align:right;float:right'><font color=\"" . $textColor . "\">&nbsp;";
			echo "<strong><font color=\"" . $textColor . "\">";
			if ($array_workload_point [$start_time] == 0) {
				echo 0;
			}else{
				echo sprintf("%.2f",$array_workload_point [$start_time]);
			}
			echo "</strong></font></div>";
		}
		echo "</br>";
	}
	return $textColor;
}

/**
 * Get days for two date differents
 * 
 * @param unknown_type $Date_1        	
 * @param unknown_type $Date_2        	
 */
function getDateDifferent($Date_1, $Date_2) {
	$Date_List_a1 = explode ( "-", $Date_1 );
	$Date_List_a2 = explode ( "-", $Date_2 );
	$d1 = mktime ( 0, 0, 0, $Date_List_a1 [1], $Date_List_a1 [2], $Date_List_a1 [0] );
	$d2 = mktime ( 0, 0, 0, $Date_List_a2 [1], $Date_List_a2 [2], $Date_List_a2 [0] );
	return $Days = round ( ($d1 - $d2) / 3600 / 24 );
}
function template_echo_date_info($date_time) {
	global $current_user;
	$dateFormat = $current_user->getUserDateTimePreferences ();
	$first_day = $date_time->get_day_by_days_from_today ( 0 );
	$last_day = $date_time->get_day_by_days_from_today ( 12 );
	
	for($i = 0; $i < strlen ( $dateFormat ['date'] ); $i ++) {
		switch ($dateFormat ['date'] {$i}) {
			case "Y" :
				echo " " . $first_day->year;
				break;
			case "m" :
				echo " " . $first_day->get_month_name ();
				break;
			case "d" :
				echo " " . $first_day->get_day ();
				break;
		}
	}
	echo " - ";
	for($i = 0; $i < strlen ( $dateFormat ['date'] ); $i ++) {
		switch ($dateFormat ['date'] {$i}) {
			case "Y" :
				echo " " . $last_day->year;
				break;
			case "m" :
				echo " " . $last_day->get_month_name ();
				break;
			case "d" :
				echo " " . $last_day->get_day ();
				break;
		}
	}
}
function template_get_next_calendar(& $args) {
	global $current_language;
	$current_module_strings = return_module_language ( $current_language, 'edanz_Schedule' );
	?>
<a
	href="index.php?action=index&module=edanz_Schedule&view=<?php echo $args['calendar']->view; ?>&<?php echo $args['calendar']->get_next_date_str(); ?>"><?php echo $current_module_strings["LBL_NEXT"]; ?>&nbsp;<?php echo SugarThemeRegistry::current()->getImage('calendar_next','alt="'. $current_module_strings["LBL_NEXT"].'" align="absmiddle" border="0"'); ?></a>
<?php
}
function template_get_previous_calendar(& $args) {
	global $current_language;
	$current_module_strings = return_module_language ( $current_language, 'edanz_Schedule' );
	
	?>
<a
	href="index.php?action=index&module=edanz_Schedule&view=<?php echo $args['calendar']->view; ?>&<?php echo $args['calendar']->get_previous_date_str(); ?>"><?php echo SugarThemeRegistry::current()->getImage('calendar_previous','alt="'. $current_module_strings["LBL_PREVIOUS"].'" align="absmiddle" border="0"'); ?>&nbsp;&nbsp;<?php echo $current_module_strings["LBL_PREVIOUS"]; ?></a>
<?php
}
?>
<script type="text/javascript" language="Javascript" defer="defer">
// window.location.hash= '#001';
var allEditors = null;
function receiveMessage(event)
{
  // Do we trust the sender of this message?
//  if (event.origin !== "http://example.com:8080")
  //  return;
//alert("message:"+event.data+",\n this message is from"+event.origin+",\n ******for testing please ignore*******");
allEditors = event.data;
  // event.source is window.opener
  // event.data is "hello there!"
  // Assuming you've verified the origin of the received message (which
  // you must do in any case), a convenient idiom for replying to a
  // message is to call postMessage on event.source and provide
  // event.origin as the targetOrigin.
  event.source.postMessage("recevied Editors success", 
                           event.origin);
}

window.addEventListener("message", receiveMessage, false);
</script>

